﻿if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (elt /*, from*/) {
        var len = this.length >>> 0;
        var from = Number(arguments[1]) || 0;
        from = (from < 0)
             ? Math.ceil(from)
             : Math.floor(from);
        if (from < 0)
            from += len;
        for (; from < len; from++) {
            if (from in this &&
                this[from] === elt)
                return from;
        }
        return -1;
    };
}

String.prototype.replaceAll = function (AFindText, ARepText) {
    raRegExp = new RegExp(AFindText, "g");
    return this.replace(raRegExp, ARepText);
}

var validator;

function saveValidate(id) {
    validator = $("#" + id).kendoValidator().data("kendoValidator");
    return validator.validate();
}

var _validationMessage = {
    CN: {
        required: "此项不能为空",
        groupRequire: "至少要选择一项",
        webSiteRequire: "请选择网页语言",
        number: "请输入数字",
        url: "URL地址格式不正确",
        email: "电子邮件地址格式不正确",
        emailExists: "该邮箱已注册",
        notAllow: "不支持chacuo.net结尾的邮箱进行注册",
        userNameExists: "该用户名已注册",
        mobile: "请输入手机号码",
        maxLen: "最大长度不能超过{0}",
        minLen: "最小长度不能小于{0}",
        fileType: "只允许上传{0}类型",
        fileType2: "不允许上传exe文件",
        fileSize: "只允许上传{0}以内的文件",
        password: "两次密码输入不一致",
        alpha: "请输入字母,数字或者汉字",
        alpha2: "请输入字母,数字,下划线(_),连字符(-)",
        alpha3: "不能包含特殊字符",
        alpha4: "不能包含中文字符",
        startDate: "开始时间不能大于结束时间",
        endDate: "结束时间不能小于开始时间",
        url2: "URL地址格式不正确",
        uniquefieldEmail: "该邮箱已注册，请使用其他邮箱",
        uniquefieldMobile: "该手机已注册，请使用其他手机",
        uniquefield_Company: "公司名已注册",
        phoneInteger: "请输入正确的数字",
        uniquefield_CompanyOut: "公司名已注册",
        uniquefield_cDomainname: "此域名已被使用",
        uniquefield_roleName: "此角色名已存在",
        uniquefield_TagName: "此标签名已存在",
        uniquefield_EventDomainName: "公司活动已存在此域名",
},
EN: {
    required: "The field is can not be empty",
    groupRequire: "Please select one item at least",
    webSiteRequire: "Please choose the language of the web",
    number: "Please enter the digit",
    url: "The URL is not in the correct format",
    email: "The Email is not in the correct format",
    emailExists: "The Email has been registered",
    notAllow: "Does not support chacuo.net at the end of the email to register",
    userNameExists: "The User Name has been registered",
    mobile: "Please enter the mobile phone numbers",
    maxLen: "The maximum length is not more than {0}",
    minLen: "The minimum length is not less than {0}",
    fileType: "Only allowed to upload the {0} file type",
    fileType2: "Not allowed to upload type of exe file",
    fileSize: "Only allowed to upload file smaller than {0}",
    password: "Two password input is not caused",
    alpha: "Please enter letters, numbers or characters",
    alpha2: "Please enter letters, numbers, '_', '-'",
    alpha3: "Cannot contain special characters",
    alpha4: "Cannot contain Chinese characters",
    startDate: "Start time not later than the end of time",
    endDate: "End time can not be earlier than the start time",
    url2: "The URL is not in the correct format",
    uniquefieldEmail: "The email has been registered, please use the other email",
    uniquefieldMobile: "The mobile has been registered, please use the other mobile",
    uniquefield_Company: "公司名已注册",
    phoneInteger: "Please input correct number",
    uniquefield_CompanyOut: "公司名已注册",
    uniquefield_cDomainname: "此域名已被使用",
    uniquefield_roleName: "此角色名已存在",
    uniquefield_TagName: "此标签名已存在",
    uniquefield_EventDomainName: "公司活动已存在此域名",
},
    CH: {
        required: "此項不能為空",
        groupRequire: "至少要选择壹項",
        webSiteRequire: "請選擇網頁語言",
        number: "請輸入數字",
        url: "URL地址格式不正確",
        email: "電子郵件地址格式不正確",
        emailExists: "該電子郵件地址已註冊",
        notAllow: "不支持chacuo.net結尾的郵箱進行註冊",
        userNameExists: "該用戶名已註冊",
        mobile: "請輸入手機號碼",
        maxLen: "最大長度不能超過{0}",
        minLen: "最小長度不能小於{0}",
        fileType: "只允許上傳{0}類型",
        fileType2: "不允許上傳exe类型",
        fileSize: "只允許上傳{0}以內的文件",
        password: "兩次密碼輸入不壹致",
        alpha: "請輸入字母，數位或者漢字",
        alpha2: "請輸入字母，數位,'_','-'",
        alpha3: "不能包含特殊字符",
        alpha4: "不能包含中文字元",
        startDate: "開始時間不能晚於結束時間",
        endDate: "結束時間不能早於開始時間",
        url2: "URL地址格式不正確",
        uniquefieldEmail: "該郵箱已注册，請使用其他郵箱",
        uniquefieldMobile: "該手機已注册，請使用其他手機",
        uniquefield_Company: "公司名已注册",
        phoneInteger: "請輸入正確的數位",
        uniquefield_CompanyOut: "公司名已注册",
        uniquefield_cDomainname: "此域名已被使用",
        uniquefield_roleName: "此角色名已存在",
        uniquefield_TagName: "此标签名已存在",
        uniquefield_EventDomainName: "公司活动已存在此域名",
    }
};


//不能為空
kendo.ui.validator.rules.required = function (input) {
    if (input.is('[required]') && $.trim(input.val()).length <= 0 && !input.is(":hidden")) {
        if (input.attr("data-role") != null && input.attr("name")) {
            if (!$('span.k-invalid-msg[data-for="' + input.attr("name") + '"]').length) {
                input.parents('.k-widget').after('<span class="k-invalid-msg" data-for="' + input.attr("name") + '"></span>');
            }
        }
        return false;
    }
    return true;
};
kendo.ui.validator.messages.required = function (input) {
    return kendo.format(_validationMessage[getCurrentLang()]["required"]);
};

kendo.ui.validator.rules.required_show = function (input) {
    if (input.is('[required_show]')) {
        if (input.attr('required_show') == "hide" && input.is(":hidden"))
            return true;
        return $.trim(input.val()).length > 0;
    }
    return true;
};
kendo.ui.validator.messages.required_show = function (input) {
    return kendo.format(_validationMessage[getCurrentLang()]["required"]);
};

//电话多字段验证
kendo.ui.validator.rules.phoneInteger = function (input) {
    if (input.is('[phoneInteger]') && !input.is(":hidden") && input.val()) {
        return /^[0-9]*[1-9][0-9]*$/.test(input.val());
    }
    return true;
};
kendo.ui.validator.messages.phoneInteger = function (input) {
    return kendo.format(_validationMessage[getCurrentLang()]["phoneInteger"]);
};

//开始时间
kendo.ui.validator.rules.startDate = function (input) {
    if (input.is('[startDate]') && !input.is(":hidden")) {
        var endField = $('#' + input.attr('endDate'));
        if (!endField.is(":hidden") && endField.val() && input.val()) {
            var startDateTime = new Date(input.val().replace(/-/g, "/"));
            var endDateTime = new Date(endField.val().replace(/-/g, "/"));
            if (startDateTime > endDateTime && input.attr("name")) {
                if (!$('span .k-invalid-msg [data-for="' + input.attr("name") + '"]').length) {
                    input.parents('.k-widget').after('<span class="k-invalid-msg" data-for="' + input.attr("name") + '"></span>');
                }
                return false;
            }
        }
    }
    return true;
};
kendo.ui.validator.messages.startDate = function (input) {
    return kendo.format(_validationMessage[getCurrentLang()]["startDate"]);
};

//结束时间
kendo.ui.validator.rules.endDate = function (input) {
    if (input.is('[endDate]') && !input.is(":hidden")) {
        var startField = $('#' + input.attr('startDate'));
        if (!startField.is(":hidden") && startField.val() && input.val()) {
            var endDateTime = new Date(input.val().replace(/-/g, "/"));
            var startDateTime = new Date(startField.val().replace(/-/g, "/"));
            if (startDateTime > endDateTime && input.attr("name")) {
                if (!$('span .k-invalid-msg [data-for="' + input.attr("name") + '"]').length) {
                    input.parents('.k-widget').after('<span class="k-invalid-msg" data-for="' + input.attr("name") + '"></span>');
                }
                return false;
            }
        }
    }
    return true;
};
kendo.ui.validator.messages.endDate = function (input) {
    return kendo.format(_validationMessage[getCurrentLang()]["endDate"]);
};

//checkbox,radio必选(name相同)
kendo.ui.validator.rules.groupRequire = function (input) {
    if (input.is('[groupRequire]') && !input.is(":hidden") && input.attr("name")) {
        var itemName = input.attr('name');
        if ($('input[name=' + itemName + ']:checked').length == 0) {
            if (!$('span.k-invalid-msg[data-for="' + input.attr("name") + '"]').length) {
                input.parents('.valid-group').after('<span class="k-invalid-msg" data-for="' + input.attr("name") + '"></span>');
            }
            return false;
        }
    }
    return true;
};
kendo.ui.validator.messages.groupRequire = function (input) {
    return _validationMessage[getCurrentLang()]["groupRequire"];
};

kendo.ui.validator.rules.webSiteRequire = function (input) {
    if (input.is('[webSiteRequire]') && !input.is(":hidden") && input.attr("name")) {
        var itemName = input.attr('name');
        return $('input[name=' + itemName + ']:checked').length > 0;
    }
    return true;
};
kendo.ui.validator.messages.webSiteRequire = function (input) {
    return _validationMessage[getCurrentLang()]["webSiteRequire"];
};

//数字
kendo.ui.validator.messages.number = function (input) {
    return kendo.format(_validationMessage[getCurrentLang()]["number"]);
};

//url
kendo.ui.validator.messages.url = function (input) {
    return kendo.format(_validationMessage[getCurrentLang()]["url"]);
};

//email
kendo.ui.validator.messages.email = function (input) {
    return kendo.format(_validationMessage[getCurrentLang()][input.attr("msgType")]);
};
kendo.ui.validator.rules.email = function (input) {
    if (input.is('[email]')) {
        if (input.val()) {
            if (/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(input.val())) {
                if (input.val().toLocaleLowerCase().indexOf("chacuo.net") > -1) {
                    input.attr("msgType", "notAllow");
                    return false;
                }
            } else {
                input.attr("msgType", "email");
                return false;
            }
        }
    }
    return true;
};

//手机号码
//kendo.ui.validator.rules.mobile = function (input) {
//    if (input.is('[mobile]')) {
//        if (input.val()) {
//            return /^(13[0-9]|15[012356789]|18[0-9]|14[57]|17[0-9])[0-9]{8}$/i.test(input.val());
//        }
//    }
//    return true;
//};
//kendo.ui.validator.messages.mobile = function (input) {
//    return kendo.format(_validationMessage[getCurrentLang()]["mobile"]);
//};

kendo.ui.validator.rules.mobile = function (input) {
    if (input.is('[mobile]') && !input.is(":hidden") && input.val()) {
        return /^[0-9]*$/g.test(input.val());
    }
    return true;
}
kendo.ui.validator.messages.mobile = function (input) {
    return kendo.format(_validationMessage[getCurrentLang()]["mobile"]);
};

//汉字,字母,数字（允许中间空格）
kendo.ui.validator.rules.alpha = function (input) {
    if (input.is('[alpha]')) {
        input.val($.trim(input.val()));//截取前后空格
        var val = /^([\u4E00-\uFA29]|\w|\s)+$/;
        if ($.trim(input.val()) == "") {
            return true;
        }
        return val.test(input.val());
    }
    return true;
};
kendo.ui.validator.messages.alpha = function (input) {
    return _validationMessage[getCurrentLang()]["alpha"];
};

//汉字,字母,下划线，连字符
kendo.ui.validator.rules.alpha2 = function (input) {
    if (input.is('[alpha2]')) {
        input.val($.trim(input.val()));//截取前后空格
        var val = /^(\w|\-|\s)+$/;
        if ($.trim(input.val()) == "") {
            return true;
        }
        return val.test(input.val());
    }
    return true;
};
kendo.ui.validator.messages.alpha2 = function (input) {
    return _validationMessage[getCurrentLang()]["alpha2"];
};


//不能包含特殊字符（ 比如：<，>）
kendo.ui.validator.rules.alpha3 = function (input) {
    if (input.is('[alpha3]')) {
        input.val($.trim(input.val()));//截取前后空格
        var val = /^[^\<>]*$/;
        if ($.trim(input.val()) == "") {
            return true;
        }
        return val.test(input.val());
    }
    return true;
};
kendo.ui.validator.messages.alpha3 = function (input) {
    return _validationMessage[getCurrentLang()]["alpha3"];
};

//字母,数字,符号
kendo.ui.validator.rules.alpha4 = function (input) {
    if (input.is('[alpha4]')) {
        input.val($.trim(input.val()));//截取前后空格
        var val = /^([\u4E00-\uFA29])+$/;
        if ($.trim(input.val()) == "") {
            return true;
        }
        return !val.test(input.val());
    }
    return true;
};
kendo.ui.validator.messages.alpha4 = function (input) {
    return _validationMessage[getCurrentLang()]["alpha4"];
};

//最大长度
kendo.ui.validator.rules.maxLen = function (input) {
    if (input.is('[maxLen]') && !input.is(":hidden")) {
        return $.trim(input.val()).length <= input.attr('maxLen');
    }
    return true;
};
kendo.ui.validator.messages.maxLen = function (input) {
    var len = input.attr('maxLen');
    return kendo.format(_validationMessage[getCurrentLang()]["maxLen"], len);
};

//最小长度
kendo.ui.validator.rules.minLen = function (input) {
    if (input.is('[minLen]') && !input.is(":hidden")) {
        return input.val().length >= input.attr('minLen');
    }
    return true;
};
kendo.ui.validator.messages.minLen = function (input) {
    var len = input.attr('minLen');
    return kendo.format(_validationMessage[getCurrentLang()]["minLen"], len);
};

//密码验证
kendo.ui.validator.rules.dataType = function (input) {
    if (input.is('[dataType]') && input.attr('dataType') == 'password') {
        var passwords = $('input[dataType=password]');
        if (passwords.length == 2) {
            if (passwords[0].value.length > 0 && passwords[1].value.length > 0) {
                return $(passwords[0]).val() == $(passwords[1]).val();
            }
        }
    }
    return true;
};
kendo.ui.validator.messages.dataType = function (input) {
    return kendo.format(_validationMessage[getCurrentLang()]["password"]);
};

//文件格式验证
kendo.ui.validator.rules.fileType = function (input) {
    if (input.is('[fileType]') && $(input).val()) {
        var filepath = $(input).val();
        var extStart = filepath.lastIndexOf(".");
        var ext = filepath.substring(extStart, filepath.length).toLowerCase();
        if (ext == ".exe") return false;
        var fileType = input.attr('fileType').split('||');
        return fileType.indexOf(ext) >= 0;
    }
    return true;
};
kendo.ui.validator.messages.fileType = function (input) {
    var fileType = input.attr('fileType');
    var filepath = $(input).val();
    var extStart = filepath.lastIndexOf(".");
    var ext = filepath.substring(extStart, filepath.length).toLowerCase();
    if (ext == ".exe")
        return kendo.format(_validationMessage[getCurrentLang()]["fileType2"]);
    return kendo.format(_validationMessage[getCurrentLang()]["fileType"], fileType.split('||').join(', '));
};

//文件大小验证
kendo.ui.validator.rules.fileSize = function (input) {
    if (input.is('[fileSize]') && $(input).val()) {
        var file_size = 0;
        var fileSize = input.attr('fileSize');
        if (/msie/.test(navigator.userAgent.toLowerCase())) {
            var img = new Image();
            img.src = $(input).val();
            if (img.fileSize > 0) {
                if (img.fileSize > parseFloat(fileSize) * 1024) {
                    return false;
                }
            }
        } else {
            file_size = input[0].files[0].size;
            var size = file_size / 1024 / 1024;
            if (size > parseFloat(fileSize)) {
                return false;
            }
        }
    }
    return true;
};
kendo.ui.validator.messages.fileSize = function (input) {
    var fileSize = input.attr('fileSize');
    var floatSize = parseFloat(fileSize);
    return kendo.format(_validationMessage[getCurrentLang()]["fileSize"], floatSize >= 1 ? fileSize + "MB" : (floatSize * 1024).toFixed(0) + "KB");
};

//匹配格式：www.mymova.com
kendo.ui.validator.rules.url2 = function (input) {
    if (input.is('[url2]')) {
        var val = /^([a-zA-Z0-9\.\-]+\.(com|cn|us|org|info|edu|net|so|co|cc|tv|biz|me|tel|io)(:\d+)?([a-zA-Z0-9\.\-~!@#$%^&*+?:_\/=<>]*)?)?$/;
        return val.test(input.val());
    }
    return true;
};
kendo.ui.validator.messages.url2 = function (input) {
    return kendo.format(_validationMessage[getCurrentLang()]["url2"]);
};

//唯一标识验证
kendo.ui.validator.rules.uniquefield = function (input) {
    if (input.is('[uniquefield]') && $.trim(input.val()).length > 0 && !input.is(":hidden")) {
        var isExists = "0";
        switch (input.attr("data-field")) {
            case "Company":
                {
                    $.ajax({
                        type: "get",
                        url: "/Manage/User/CheckCompanyName",
                        data: { "name": input.val() },
                        async: false,
                        success: function (data) {
                            isExists = data;
                        }
                    });
                }
                break;
            case "ContactEmail": /*注册页面特殊逻辑控制*/
                {
                    $.ajax({
                        type: "get",
                        url: "/Manage/User/CheckContactEmail",
                        data: { "email": input.val() },
                        async: false,
                        success: function (data) {
                            isExists = data;
                        }
                    });
                    if (isExists == "1") {
                        $('#email-exsit').show();
                        $('#ConfirmPassword').hide()
                            .parents('li').hide();
                        $('span[data-for="ConfirmPassword"]').hide();
                        return true;
                    } else {
                        $('#email-exsit').hide();
                        $('#ConfirmPassword').show()
                            .parents('li').show();
                    }
                }
                break;
            case "CompanyOut"://add by lqch
                {
                    var oldName = $.trim($("#oldName").val());
                    if (oldName == $.trim(input.val())) return true;//如果没有修改名称则不去后台
                    var _data = {
                        CompanyName: $.trim(input.val()),
                    };



                    $.ajax({
                        url: "/Manage/Account/CheckCompanyName",
                        type: "POST",
                        async: false,
                        contentType: "application/json",
                        data: JSON.stringify(_data),
                        success: function (r) {
                            var re = eval('(' + r + ')');
                            isExists = re.Success ? "1" : "0";
                        }
                    });
                }
                break;
            case "cDomainname"://add by lqch
                {
                    var _data = {
                        DomainName: $.trim(input.val()),
                    };
                    $.ajax({
                        url: "/Manage/Account/CheckDomainName",
                        type: "POST",
                        async: false,
                        contentType: "application/json",
                        data: JSON.stringify(_data),
                        success: function (r) {
                            var re = eval('(' + r + ')');
                            isExists = re.Success ? "1" : "0";
                        }
                    });
                }
                break;
            case "email":
                {
                    try {
                        var newVal = $.trim(input.val());
                        var oldVal = $.trim($("#OldEmail").val());
                        if (newVal == oldVal) return true;
                        $.ajax({
                            type: "GET",
                            url: "/Manage/Account/CheckEmail",
                            data: { "email": input.val() },
                            async: false,
                            success: function (data) {
                                var rsp = eval("(" + data + ")");
                                isExists = rsp.Status;
                                if (isExists == 0) {
                                    $("#pwd").show();
                                    //$("#UserName").val("");
                                    $("#OldEmail").val("");
                                } else {
                                    $("#pwd").hide();
                                    $("#OldEmail").val(input.val());
                                    $("#UserName").val(rsp.ExtensionData);
                                }
                            }
                        });
                    } catch (ex) {
                        console.log(ex);
                    }
                }
                break;

            case "roleName"://add by lqch
                {
                    var oldName = $.trim($("#oldName").val());
                    if (oldName == $.trim(input.val())) return true;//如果没有修改名称则不去后台

                    var _data = {
                        Name: $.trim(input.val()),
                        Id: $.trim($("#Id").val()),
                    };
                    $.ajax({
                        url: "/Manage/Account/CheckRoleName",
                        type: "POST",
                        async: false,
                        contentType: "application/json",
                        data: JSON.stringify(_data),
                        success: function (r) {
                            var re = eval('(' + r + ')');
                            isExists = re.Success ? "1" : "0";
                        }
                    });
                }
                break;
            case "TagName"://add by lqch
                {
                    var oldName = $.trim($("#tagNameHidden").val());
                    if (oldName == $.trim(input.val())) return true;//如果没有修改名称则不去后台
                    var _data = {
                        TagName: $.trim(input.val()),
                        tagId : $.trim($("#tagId").val()),
                    };

                    $.ajax({
                        url: "/Manage/Home/CheckTagUniquefield",
                        type: "POST",
                        async: false,
                        contentType: "application/json",
                        data: JSON.stringify(_data),
                        success: function (r) {
                            var re = eval('(' + r + ')');
                            isExists = re.Success ? "1" : "0";
                        }
                    });
                }
                break;
            case "EventDomainName"://不同语言的活动DomainName add by lqch
                var oldName = $.trim($("#EventDomainNameHidden").val());
                if (oldName == $.trim(input.val())) return true;//如果没有修改名称则不去后台
                var _data = {
                    DomainName: $.trim(input.val()),
                    Id: $.trim($("#Id").val()),
                };

                $.ajax({
                    url: "/Manage/EventPromo/CheckEventDomainName",
                    type: "POST",
                    async: false,
                    contentType: "application/json",
                    data: JSON.stringify(_data),
                    success: function (r) {
                        var re = eval('(' + r + ')');
                        isExists = re.Success ? "1" : "0";
                    }
                });
                break;
            case "Enroll":
                $('.unique-msg').remove();
                $.ajax({
                    url: enrollUrl+"/CheckEnrollUnique",
                    type: "POST",
                    async: false,
                    data: {value:input.val(),uniqueFlag:input.attr("name")},
                    success: function (r) {
                        var re = eval('(' + r + ')');
                        isExists = re.Success?"1":"0";
                        if (isExists=="1") {
                            input.parents("li").after('<li class="lierr unique-msg"><span class="k-widget k-tooltip k-tooltip-validation k-invalid-msg" role="alert"><span class="k-icon k-warning"> </span> ' + re.Message + '</span></li>');
                        }
                    }
                });
            default:
        }
        return (isExists == "0");
    }
    return true;
};
kendo.ui.validator.messages.uniquefield = function (input) {
    return kendo.format(_validationMessage[getCurrentLang()]["uniquefield_" + input.attr('data-field')]);
};

//优先根据隐藏变量判断语言类型,其次根据url判断,以上不成立时返回中文简体
function getCurrentLang() {
    if ($('#_lang').length == 1) {
        if (_validationMessage[$('#_lang').val()])
            return $('#_lang').val();
    }
    return "CN";
}

//单独对控件设置错误提示
function setErrorMsg(target, message) {
    if ($('[name="' + target + '"]')) {
        var _self = $('[name="' + target + '"]');
        var _errorLabel = $('span[data-for="' + _self.attr("name") + '"][class*="k-invalid-msg"]');
        if (!_errorLabel.length) {
            var _ctr = _self;
            if (_self.attr("data-role") != null && _self.attr("name")) {
                _ctr = _self.parents('.k-widget');
            }
            _ctr.after('<span class="k-widget k-tooltip k-tooltip-validation k-invalid-msg" data-for="' + _self.attr("name") + '" role="alert"><span class="k-icon k-warning"> </span> ' + message + '</span>');
        } else {
            _errorLabel.addClass('k-widget k-tooltip k-tooltip-validation').html('<span class="k-icon k-warning"> </span> ' + message).show();
        }
        //_self.focus();
    } else {
        alert(message);
    }
    return false;
}

function vilidationEmail(value) {
    if (/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(value)) {
        if (value.toLocaleLowerCase().indexOf("chacuo.net") > -1) {
            return false;
        } else return true;
    }
    return false;
}

function vilidationTel(value) {
    return /^[0-9]*[1-9][0-9]*$/.test(value);
}